var express = require('express');
var router = express.Router();
const { User } = require('../../models');
const { Op } = require('sequelize');

const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');

/* GET home page. */
router.get('/', async function (req, res, next) {
    try {
        const query = req.query;
        // 页和每页现实几条数据
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;

        const offset = (currentPage - 1) * pageSize;

        const condition = {
            order: [['id', 'DESC']],
            offset: offset,
            limit: pageSize,
            where: {}
        }
        if (query.email) {
            condition.where.email = {
                [Op.eq]: query.email
            }
        }
        if (query.username) {
            condition.where.username = {
                [Op.eq]: query.username
            }
        }
        if (query.role) {
            condition.where.role = {
                [Op.eq]: query.role
            }
        }
        if (query.nickname) {
            condition.where.nickname = {
                [Op.like]: `%${query.nickname}%`
            }
        }
        console.log('condition-->',condition)
        const { count, rows } = await User.findAndCountAll(condition);
        success(
            res,
            '查询用户列表成功',
            {
                user: rows,
                pagination: {
                    total: count,
                    currentPage,
                    pageSize
                }
            }
        )
    } catch (error) {
        failure(res, error)
    }
});

// 查询用户详情
router.get('/:id', async function (req, res, next) {
    try {
        const user = await getUser(req);
        success(
            res,
            '查询用户成功',
            {user}
        )

    } catch (error) {
        failure(res, error)
    }
});


// 新建用户
router.post('', async function (req, res, next) {
    try {
        const body = filterBody(req.body)
        const user = await User.create(body)
        success(
            res,
            '创建用户成功',
            {user}
        )
    } catch (error) {
        failure(res, error)
    }
});

// 删除用户
// router.delete('/:id', async function (req, res, next) {
//     try {
//         const user = await getUser(req);
//         await user.destroy()
//         success(
//             res,
//             '删除用户成功'
//         )
//     } catch (error) {
//         failure(res, error)
//     }
// });

// 更新用户
router.put('/:id', async function (req, res, next) {
    try {
        const user = await getUser(req);
        const body = filterBody(req.body)
        await user.update(body)
        success(
            res,
            '更新用户成功', {
                user
            }
        )
    } catch (error) {
        failure(res, error)
    }
});

// 过滤body 和 name
const filterBody = (body)=>{
    return {
        email: body.email,
        username: body.username,
        password: body.password,
        nickname: body.nickname,
        sex: body.sex,
        company: body.company,
        introduce: body.introduce,
        role: body.role,
        avatar: body.avatar,
    }
}


/**
 * 查询当前用户
 * @param {*} req 
 */
async function getUser(req) {
    const { id } = req.params;
    const user = await User.findByPk(id);
    if (!user) {
        throw new NotFoundError(`ID: ${id}的用户未找到`)
    }
    return user;
}

module.exports = router;
